<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="formRef"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="ruleForm.roleName"></el-input>
    </el-form-item>
    <el-form-item label="角色权限" prop="permission"> </el-form-item>
    <el-tree
      :data="mainRoutes"
      show-checkbox
      :props="defaultProps"
      node-key="path"
      ref="treeRef"
      @check="handleCheck"
    />
    <el-form-item>
      <el-button type="primary" @click="submitForm">
        {{ roleData ? "修改" : "新增" }}
      </el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { rolePost, rolePut } from "@/api/user.js";
import { mainRoutes } from "@/router/index";
export default {
  props: ["roleData"],
  data() {
    return {
      mainRoutes,
      defaultProps: {
        // label: "path", //告知tree，以path作为tree的渲染文字
        label: (item) => item.meta.label, //将函数的返回值作为tree的渲染文字
      },
      ruleForm: {
        roleName: "",
        permission: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        permission: [
          { required: true, message: "请勾选角色权限", trigger: "change" },
        ],
      },
      cateList: [], //下拉列表数据
    };
  },
  watch: {
    roleData(newVal, prevVal) {
      console.log("watch监听", newVal, prevVal);
      if (newVal) {
        let { roleName, permission } = newVal;
        this.ruleForm.roleName = roleName;
        this.ruleForm.permission = permission;
        this.$refs.treeRef.setCheckedKeys(permission); //动态设置tree组件勾选状态
      } else {
        this.ruleForm.roleName = "";
        this.ruleForm.permission = [];
        this.$refs.treeRef.setCheckedKeys([]);
      }
    },
  },
  methods: {
    submitForm(formName) {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          if (this.roleData) {
            let { objectId } = this.roleData;
            rolePut(objectId, this.ruleForm).then((res) => {
              this.$emit("update-list", {
                objectId,
                ...this.ruleForm,
              });
            }); //更新
          } else {
            rolePost(this.ruleForm).then((res) => {
              this.$emit("update-list", {
                objectId: res.data.objectId,
                ...this.ruleForm,
              });
            }); //新增
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleCheck(_, { checkedKeys }) {
      // console.log(checkedKeys);
      this.ruleForm.permission = checkedKeys;
    },
  },
};
</script>
